package qq2564874169.tuaotuao.fx.orm.mybatis;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;

import java.sql.Connection;
import java.sql.Statement;
import java.util.Properties;

@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class SetTimeoutInterceptor implements Interceptor {
    private static ThreadLocal<Integer> tag = new ThreadLocal<>();

    void setTimeout(int second) {
        tag.set(second);
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object data = invocation.proceed();
        Integer time = tag.get();
        if (time != null) {
            tag.remove();
            ((Statement) data).setQueryTimeout(time);
        }
        return data;
    }

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
